"""A simple file backup script."""

import os
import shutil
from datetime import datetime
import logging

SOURCE = ['D:\\Desktop\\1', 'D:\\Desktop\\1.txt']
DESTINATION = 'D:\\BackupFile - Python\\'
LOG_DIRECTORY = 'LogFiles'
RECYCLE_BIN = 'Recycle Bin'

# log
# print(os.path.join(DESTINATION, LOG_DIRECTORY))
if not os.path.exists(os.path.join(DESTINATION, LOG_DIRECTORY)):
    os.makedirs(os.path.join(DESTINATION, LOG_DIRECTORY))

logging.basicConfig(level=logging.INFO,
                    filename=os.path.join(DESTINATION, LOG_DIRECTORY, datetime.today().strftime('%Y-%m-%d-%H%M%S') + '.log'),
                    filemode='x',
                    format='%(asctime)s:%(levelname)s:%(message)s')
# backup
logging.info('Start Backuping.')
for source in SOURCE:
    # source item exists
    if os.path.exists(source):
        # source item is directory
        if os.path.isdir(source):
            source_drive = os.path.splitdrive(source)[0]
            source_destination = os.path.join(DESTINATION, source[0])
            # destination directory
            dd = source.replace(source_drive, source_destination)
            # destination directory not exists
            if not os.path.exists(dd):
                os.makedirs(dd)
                logging.info('Make directory: %s', dd)
            for dirpath, dirnames, filenames in os.walk(source):
                for dirname in dirnames:
                    # destination child directory
                    d = os.path.join(dirpath.replace(source_drive, source_destination), dirname)
                    if not os.path.exists(d):
                        os.makedirs(d)
                        logging.info('Make directory: %s', d)
                for filename in filenames:
                    s = os.path.join(dirpath, filename)
                    d = os.path.join(dirpath.replace(source_drive, source_destination), filename)
                    # des file exists
                    if os.path.isfile(d):
                        if os.path.getmtime(s) > os.path.getmtime(d):
                            shutil.copyfile(s, d)
                            logging.info('Updating file: %s', d)
                    # des file not exists
                    else:
                        shutil.copyfile(s, d)
                        logging.info('Copy file: %s', d)
        elif os.path.isfile(source):
            # des file full name
            d = source.replace(source_drive, source_destination)
            # des file exists
            if os.path.isfile(d):
                if os.path.getmtime(source) > os.path.getmtime(d):
                    shutil.copyfile(source, d)
                    logging.info('Updating file: %s', d)
            # des file not exists
            else:
                shutil.copyfile(source, d)
                logging.info('Copy file: %s', d)
# cleaning
logging.info('Start Cleaning.')
if not os.path.exists(os.path.join(DESTINATION, RECYCLE_BIN)):
    os.makedirs(os.path.join(DESTINATION, RECYCLE_BIN))
for dirpath, dirnames, filenames in os.walk(DESTINATION):
    if RECYCLE_BIN not in dirpath and LOG_DIRECTORY not in dirpath:
        for dirname in dirnames:
            if RECYCLE_BIN not in dirname and LOG_DIRECTORY not in dirname:
                s = os.path.join(dirpath, dirname).replace(DESTINATION, '')
                if not os.path.exists(s[:1] + ':' + s[1:]):
                    os.makedirs(os.path.join(DESTINATION, RECYCLE_BIN, datetime.today().strftime('%Y-%m-%d-%H%M%S')))
                    shutil.move(os.path.join(dirpath, dirname), os.path.join(DESTINATION, RECYCLE_BIN, datetime.today().strftime('%Y-%m-%d-%H%M%S')))
                    logging.info('Recycle directory: %s', os.path.join(dirpath, dirname))
        for filename in filenames:
            s = os.path.join(dirpath, filename).replace(DESTINATION, '')
            if not os.path.exists(s[:1] + ':' + s[1:]):
                os.makedirs(os.path.join(DESTINATION, RECYCLE_BIN, datetime.today().strftime('%Y-%m-%d-%H%M%S')))
                shutil.move(os.path.join(dirpath, filename), os.path.join(DESTINATION, RECYCLE_BIN, datetime.today().strftime('%Y-%m-%d-%H%M%S')))
                logging.info('Recycle file: %s', os.path.join(dirpath, filename))
logging.info('Finish.')
